<script lang="ts" setup>
import {showToast} from 'vant';
import { ref, reactive, nextTick, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import SVGA from "svgaplayerweb";

const router = useRouter();

const wsUrl = ref<string>("ws://47.120.39.237:9999/");

import headerUtil from "./base/common/headerUtil.vue";
import redPacketUtil from "./base/common/redPacketUtil.vue";

import reqApis from "../req/reqApis.js";
import Client from '../req/common';


const svgaWrapRef = ref();


const currentData = ref<any>({
  redPacketConfigCode: null,
  sendRedPacketStatus: 0,
  redPacketBool: false,
  canvas: {},
  player: {},
  parser: {},
  // canvasBool: false,
  showBottom: false,
  uniqueCode: router.currentRoute.value.query.uniqueCode,
  groupName: router.currentRoute.value.query.groupName,
  curUser: {},
  websock: null,
  chatList: [],
  content: "",
  headerObj:{
    showType: 2,
    closeBtn: false
  },
  timer: null

});

const scrollOutRef = ref();


const getChatInfoList = () => {
  if(currentData.value.uniqueCode == null) {
    return;
  }
  reqApis.getChatInfoListApi({uniqueCode: currentData.value.uniqueCode}).then(res => {
    currentData.value.chatList.push(...res.data);
    initTop();
  })
  
}


const websocketSend = (data: any) => {//数据发送
    currentData.value.websock.send(data);
};

const websocketOnOpen = () => {
    console.log('初始化连接建立');
};

const websocketOnError = () => {
    console.error('出现异常');
};
const websocketClose = (e:any) => {  //关闭
    console.log('断开连接', e);
};

const startHeartBeatJob = () => { // 每三秒发送一次心跳包
    console.log('首次登录成功');
    //发送一个心跳包给到服务端
    let jsonStr = {"userId": currentData.value.curUser.userId, "appId": 10001};
    let bodyStr = JSON.stringify(jsonStr);
    let heartBeatJsonStr = {"magic": 19231, "code": 1004, "len": bodyStr.length, "body": bodyStr};
    clearInterval(currentData.value.timer);
    currentData.value.timer = setInterval(() => {
      if (currentData.value.websock.readyState === WebSocket.OPEN) {
        websocketSend(JSON.stringify(heartBeatJsonStr));
      }else{
        clearInterval(currentData.value.timer);
      }
      
    }, 3000);
};

const sendAckCode = (respData: any) =>  {
  let jsonStr = {uniqueCode: currentData.value.uniqueCode, "userId": currentData.value.curUser.userId, "appId": 10001,"msgId":respData.msgId};
  let bodyStr = JSON.stringify(jsonStr);
  let ackMsgStr = {"magic": 19231, "code": 1005, "len": bodyStr.length, "body": bodyStr};
  websocketSend(JSON.stringify(ackMsgStr));
};


const websocketOnMessage = (e:any) => { //数据接收
  let wsData = JSON.parse(e.data);
  if(wsData.code == 1001) {
      startHeartBeatJob();
  } else if (wsData.code == 1003) {
      // let respData = JSON.parse(Client.utf8ByteToUnicodeStr());
    let respData = JSON.parse(wsData.bodyStr);
    //属于直播间内的聊天消息
    if(respData.bizCode==5555) {
      let respMsg = JSON.parse(respData.data);
      let sendMsg = {"userId": respMsg.userId, "content": respMsg.content, "senderName": respMsg.senderName, "senderImg": respMsg.senderAvtar};
      let msgWrapper = {"msgType": 1, "msg": sendMsg};
      currentData.value.chatList.push(msgWrapper);
      initTop();
      //发送ack确认消息
    } else if (respData.bizCode == 5560) {
        if(currentData.value.redPacketBool == false) {
            // //开始红包雨活动
            let respMsg = JSON.parse(respData.data);
            let redPacketConfig = JSON.parse(respMsg.redPacketConfig);
            currentData.value.redPacketConfigCode = redPacketConfig.configCode;
            currentData.value.redPacketBool = true;
        }
    }
    sendAckCode(respData);
  }
};

const sendReview = () => {
    if (currentData.value.content == '') {
      showToast("评论不能为空");
        return;
    }



    let info = currentData.value.content;
    let sendMsg = {
                   "userId": currentData.value.curUser.userId, 
                   "content": info, 
                   "senderName": currentData.value.curUser.nickName, 
                   "senderImg": currentData.value.curUser.avatar};
    let msgWrapper = {"msgType": 1, "msg": sendMsg};
    currentData.value.chatList.push(msgWrapper);
    initTop();

    //发送评论消息给到im服务器  
    let msgBody = {"roomId": '470',
                  "type":1,
                  "content":info, 
                  "uniqueCode": currentData.value.uniqueCode,
                  "chatType": 1,
                  "receiveUserId": currentData.value.friendId,  
                  "senderName": currentData.value.curUser.nickName,
                   "senderAvtar": currentData.value.curUser.avatar
                   };
    let jsonStr = {"chatType":1, "userId": currentData.value.curUser.userId, "appId": 10001,"bizCode":5555,"data":JSON.stringify(msgBody), uniqueCode: currentData.value.uniqueCode};
    let bodyStr = JSON.stringify(jsonStr);
    console.log('发送消息');
    let reviewMsg = {"magic": 19231, "code": 1003, "len": bodyStr.length, "body": bodyStr};
    console.log(JSON.stringify(reviewMsg));
    websocketSend(JSON.stringify(reviewMsg));
    currentData.value.content = "";

};

// 连接IM服务器
const connectImServer = () =>  {

let IP_PORT = "47.120.39.237:9999";
  let sendUserId = currentData.value.curUser.userId;
  let uniqueCode = currentData.value.uniqueCode;
  let code = "1001";
  let appId = "10001";
  
  let url = `ws://${IP_PORT}/${sendUserId}/${appId}/${code}/${uniqueCode}`;
  
  currentData.value.websock = new WebSocket(url);
  currentData.value.websock.onmessage = websocketOnMessage;
  currentData.value.websock.onopen = websocketOnOpen;
  currentData.value.websock.onerror = websocketOnError;
  currentData.value.websock.onclose = websocketClose;
  console.log('初始化ws服务器');
};


const initTop = () => {
  currentData.value.timer = setTimeout(() => {
    scrollOutRef.value.scrollTop = scrollOutRef.value.scrollHeight;
  }, 10);
}

const scrollData = () => {
  
}


const getUserFn = () => {
  reqApis.getCurrentUserApi({}).then((res: any) => {
    currentData.value.curUser = res.data;
    getChatInfoList();
    connectImServer();
  }).catch(err => {
      console.log(err)
  });
}
const initRedPacketFn = () => {
  reqApis.getSendPermissionApi({}).then(res => {
    if(res.data != null) {
      currentData.value.sendRedPacketStatus = res.data.status;
      currentData.value.redPacketConfigCode = res.data.configCode;
    }
  })
}

const prepareRedPacketConfigFn = ()  => {
  reqApis.prepareRedPacketConfigApi({}).then(res => {
    showToast('红包数据初始化完成');
    initRedPacketFn()
  })
};
const startRedPacketFn = () => {
  reqApis.sendRedPacketApi({
    redPacketConfigCode: currentData.value.redPacketConfigCode,
    uniqueCode: currentData.value.uniqueCode
  }).then(res => {
   currentData.value.showBottom = false;
   initRedPacketFn()
  })
}



// onMounted(() => {
//   initSvga();
// })

getUserFn();
initRedPacketFn();




</script>
<template>
  <section class="groupChat">
    <headerUtil :obj="currentData.headerObj" >{{currentData.groupName}}</headerUtil>
    <redPacketUtil v-if="currentData.redPacketBool" :configCode="currentData.redPacketConfigCode" @closePacketFn="currentData.redPacketBool = false"></redPacketUtil>
    <div class="content" @scroll.passive="scrollData" ref="scrollOutRef">
      <div class="item-wrap"  v-for="(item, index) in currentData.chatList" :key="index">
        <div :class="{'face-img':true, 'right-wrap':item.msg.userId == currentData.curUser.userId, 'left-wrap':item.msg.userId != currentData.curUser.userId}" :style="{background: `url(${item.msg.senderImg}) no-repeat center`}"></div>
        <div :class="{'content-wrap':true, 'right-wrap':item.msg.userId == currentData.curUser.userId, 'left-wrap':item.msg.userId != currentData.curUser.userId}">
          <div class="name">{{item.msg.senderName}}</div>
          <div class="text">{{item.msg.content}}</div>
          </div>
      </div>
    </div>
    <div class="send-wrap">
      <div class="send-content">
        <input class="search-input" v-model="currentData.content" placeholder="输入内容" type="text">
        </div>
        <div v-if="currentData.sendRedPacketStatus != 0" @click="currentData.showBottom= true">
          <van-icon style="margin: 0 .1rem" name="point-gift" />
        </div>
        <div class="btn" @click="sendReview">发送</div>
    </div>
    <van-popup

      v-model:show="currentData.showBottom"
      position="bottom"
      :style="{ height: '30%' }"
    >
    <div class="giftWrap">
      <van-button @click="prepareRedPacketConfigFn" v-if="currentData.sendRedPacketStatus == 1" type="primary">初始化红包雨</van-button>
      <van-button @click="startRedPacketFn" v-if="currentData.sendRedPacketStatus == 2" type="success">开始派发红包雨</van-button>
    </div>
     
    </van-popup>
    <!-- <div :style="{display: currentData.canvasBool?'block':'none'}" class="svga-wrap" ref="svgaWrapRef"></div> -->
  </section>
</template>

<style lang="less" scoped>
.groupChat {
  width: 3.75rem;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  
  .giftWrap {
    display: flex;
    padding: .1rem;
    .giftItem {
      width: .5rem;
      height: .5rem;
      display: flex;
      margin-right: 0.1rem;
      background-size: cover !important;
    }
  }
  .content {
    flex: 1;
    overflow-y: auto;
    .item-wrap {
      width: 3.75rem;
      min-height: 0.6rem;
      margin: .1rem 0;
      .face-img {
        width: 0.5rem;
        height: 0.5rem;
        background-size: contain !important;
      }
      .left-wrap {
        float: left;
        .text {
          background: white;
        }
      }
      .right-wrap {
        float: right;
        text-align: right;
        .text {
          background: #9adc9a;
        }
      }
      .content-wrap {
        display: inline-block;
        min-height: 0.5rem;
        max-width: 3.2rem;
        padding: 0.05rem;
        .name {
          font-size: 0.12rem;
          padding:.02rem;
        }
        .text {
          display: inline-block;
          word-wrap: break-word;
          font-size: 0.16rem;
          line-height: 0.2rem;
          padding: 0.05rem;
          border-radius: 0.04rem;
        }
      }
    }
  }
  .send-wrap {
    height: .5rem;
    background: white;
    display: flex;
    align-items: center;
    padding: .1rem;
    .send-content {
      flex: 1;
      height: .34rem;
      background: #eff2f5;
      padding-left: .1rem;
      .search-input {
        height: 100%;
        width: 100%;
        font-size: .16rem;
        background: #eff2f5;
      }
    }
    .btn {
      width: .8rem;
      height: .34rem;
      line-height: .34rem;
      text-align: center;
      border-radius: .3rem;
      background: #1989fa;
      font-size: .16rem;
      color: white;

    }
  }
  .svga-wrap {
    z-index: 999;
    position: absolute;
    top:  -10%;
    height: 70%;
    width: 100%;
  }
}



</style>

